package com.aecc.api.base;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.aecc.api.model.ResultModel;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public abstract class BaseController {
	
	/**
	 * 统一处理系统异常，返回错误码417
	 * @param request
	 * @param e
	 * @return
	 */
	@ExceptionHandler
    public ResponseEntity<ResultModel> exception(HttpServletRequest request, Exception e) {  
		//添加自己的异常处理逻辑，如日志记录
		log.error(e.getMessage(),e);
        return this.Resp417(ResultModel.custom(-1, e.getMessage()));
	}
	
	/**
	 * 统一处理validation校验异常，返回错误码200
	 * @param e
	 * @return
	 */
	@ExceptionHandler(value = BindException.class)
	public ResponseEntity<ResultModel> bindException(BindException e){
		log.error(e.getBindingResult().getAllErrors().toString());
		return this.Resp200(ResultModel.fail(e.getBindingResult().getAllErrors().get(0).getDefaultMessage()));
	}
	
	/**得到request对象
	 * @return HttpServletRequest
	 */
	protected HttpServletRequest getRequest() {
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		return request;
	}
	
	/**
	 * 获取项目访问路径
	 * @return
	 */
	protected String getBasePath(){
		String url = this.getRequest().getRequestURL().toString();
		String contextPath = this.getRequest().getContextPath();		
		return url.substring(0,url.indexOf(contextPath)+contextPath.length());
	}
	
	/**
	 * 请求参数map
	 * @return 参数map
	 * @throws Exception 
	 * @throws  
	 */
	public Map<String,Object> getParams(){
		Map<String, Object> paramMap = new HashMap<>();
		Map<String,String[]> it = getRequest().getParameterMap();
		for(Entry<String,String[]> entry:it.entrySet()){
			if(entry.getValue().length==1){
				paramMap.put(entry.getKey(), entry.getValue()[0]);
			}else{
				paramMap.put(entry.getKey(), entry.getValue());
			}
		}
	    return paramMap;
	}
	
	/**
	 * 操作成功
	 * @param desc 描述/数据
	 * @return
	 */
	public <T> ResponseEntity<T> Resp200(T desc){
		return ResponseEntity.ok(desc);
	}
	
	/**
	 * 服务器异常导致操作失败，状态码：417
	 * @param desc 错误描述
	 * @return
	 */
	public <T> ResponseEntity<T> Resp417(T desc){
		return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(desc);
	}
	
}
